package org.budo.alipay.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.budo.support.lang.util.StringUtil;
import org.budo.support.mvcs.Mvcs;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;

/**
 * @author limingwei
 */
public class AlipayUtil {
    /**
     * 除去数组中的空值和签名参数
     * 
     * @return 去掉空值与签名参数后的新签名参数组
     */
    public static Map<String, String> parameterFilter(Map<String, String> parameters) {
        Map<String, String> map = new HashMap<String, String>();

        if (parameters == null || parameters.size() <= 0) {
            return map;
        }

        for (String key : parameters.keySet()) {
            String value = parameters.get(key);
            if (value == null || value.equals("") || key.equalsIgnoreCase("sign") || key.equalsIgnoreCase("sign_type")) {
                continue;
            }
            map.put(key, value);
        }

        return map;
    }

    /**
     * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     * 
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> params) {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);

        String prestr = "";

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);

            if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }

        return prestr;
    }

    public static boolean isAlipayUserAgent(HttpServletRequest request) {
        String userAgent = Mvcs.getUserAgent(request);
        return StringUtil.contains(userAgent, "AlipayClient");
    }

    public static AlipayTradeWapPayResponse pageExecute(AlipayClient alipayClient, AlipayTradeWapPayRequest request) {
        try {
            return alipayClient.pageExecute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }
}